import {
  getMenu,
  findDictionaryByParentValue,
  getUserRole,
  getDefaultNodeList,
  getStateList,
  getNotice
} from '@/api/app'

const state = {
  sidebar: {
    opened: true,
    withoutAnimation: false
  },
  device: 'desktop',
  btns: [],
  updateInfo: {
    flag: false,
    info: []
  }
}

const mutations = {
  SET_BTNS: (state, btns) => {
    state.btns.push(btns)
  },
  SET_ALL_BTNS(state, btns) {
    state.btns = btns
  },
  SET_UPDATE_INFO(state, updateINFO) {
    state.updateInfo = updateINFO
  }
}

const actions = {
  fetchProjectDic({
    commit
  }, payload) {
    return findDictionaryByParentValue({
      parentValue: payload.parentValue,
      sysCode: payload.sysCode
    }).then(res => {
      const data = res.data
      commit(payload.commit, data || [])
    }).catch(() => {})
  },
  getMenuInfo({
    commit
  }) {
    return new Promise((resolve, reject) => {
      getMenu().then(response => {
        const {
          data,
          errorMsg,
          success
        } = response
        if (!success) {
          reject(errorMsg || '获取菜单失败')
        }

        // roles must be a non-empty array
        if (!data || data.length <= 0) {
          reject('getInfo: menus must be a non-null array!')
        }

        commit('SET_MENUS', data)
        if (data && data.length !== 0) {
          commit('SET_MENU_TYPE', data[0].name)
        }
        filterBtns(commit, '', data)
        resolve(data)
      }).catch(error => {
        // console.log('message', error.message)
        reject('获取菜单失败')
      })
    })
  },
  getUserRole({
    commit
  }) {
    getUserRole().then((res) => {
      commit('SET_USER_ROLE_TYPE', res && res.data && res.data.roleType || '')
    }).catch(err => {
      console.error('获取用户角色失败', err.message || '')
    })
  },
  getAllBtns({ commit }, btns) {
    commit('SET_ALL_BTNS', btns)
  },
  async getUpdateInfo({ commit }) {
    const { data } = await getNotice()
    let flag = false
    if (data && data.length) {
      flag = true
    }
    commit('SET_UPDATE_INFO', {
      flag,
      info: data || []
    })
  }
}

function filterBtns(commit, parent, menus) {
  menus.forEach(menu => {
    if (menu.typeId === '1') {

      commit('SET_BTNS', `${menu.conent}`)
    } else {
      if (menu.childs) {
        menu.childs.forEach(childMenu => {
          if (childMenu.typeId === '0') {
            filterBtns(commit, childMenu, childMenu.childs)
          } else {

            commit('SET_BTNS', `${childMenu.conent}`)
          }
        })
      }
    }
  })
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
